import { ListItemType } from "../../views/home";
import {
  ADD_CAR_ITEM,
  CarActions,
  ADD_CAR_ITEM_COUNT,
  SUB_CAR_ITEM_COUNT,
  DELETE_CAR_ITEM,
  SIWTCH_CAR_ITEM_IS_CEHCKED,
  SIWTCH_ALL_IS_CHECKED
} from "./carActions";

const carReducer = (state = initState, action: CarActions) => {
  switch (action.type) {
    case ADD_CAR_ITEM:
      const item = state.car.find((v) => v.id === action.payload.id);
      if (item) {
        item.count++;
      } else {
        state.car.push({
          ...action.payload,
          count: 1,
          isChecked: false,
        });
      }
      return {
        ...state,
        car: [...state.car],
      };
    case ADD_CAR_ITEM_COUNT: {
      const item = state.car.find((v) => v.id === action.payload);
      if (item) item.count++;
      return {
        ...state,
        car: [...state.car],
      };
    }
    case SUB_CAR_ITEM_COUNT: {
      const item = state.car.find((v) => v.id === action.payload);
      if (item) item.count--;
      return {
        ...state,
        car: [...state.car],
      };
    }
    case DELETE_CAR_ITEM: {
      return {
        ...state,
        car: state.car.filter((v) => v.id !== action.payload),
      };
    }
    case SIWTCH_CAR_ITEM_IS_CEHCKED: {
      const item = state.car.find((v) => v.id === action.payload);
      if (item) item.isChecked = !item.isChecked;
      return {
        ...state,
        car: [...state.car],
      };
    }
    case SIWTCH_ALL_IS_CHECKED: {
      state.car.map(v => v.isChecked = action.payload)
      return {
        ...state,
        car: [...state.car]
      }
    }
    default:
      return state;
  }
};

interface CarState {
  car: CarItemType[];
}

interface CarItemType extends ListItemType {
  count: number;
  isChecked: boolean;
}

const initState: CarState = {
  car: [],
};

export default carReducer;
